/*
 * Copyright (C) 2011 Urals State University,
 * Department of Mathematics and Mechanics
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ru.edu.usu.cs.bubbles;

import ru.edu.usu.cs.bubbles.userlistener.UserListener;
import ru.edu.usu.cs.bubbles.utils.CoordConvertor;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class GameView extends SurfaceView implements SurfaceHolder.Callback {
	public GameThread thread;
	public UserListener on_touch;
	private String TAG = "GameView";

	public GameView(Context context, AttributeSet attrs) {
		super(context, attrs);
		SurfaceHolder holder = getHolder();
		holder.addCallback(this);

		// create thread only; it's started in surfaceCreated()
		//TODO level = 0 for worked demo version 
		Log.d(TAG, "GameView created");
		on_touch = new UserListener();
		this.setOnTouchListener(on_touch);
		thread = new GameThread(holder, context, 0, on_touch); 

		setFocusable(true);

	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		Log.d(TAG, "surfaceChanged");
		thread.setSurfaceSize(width, height);
		Log.d(TAG, "size"+this.getWidth()+" "+this.getHeight());
		Log.d(TAG, "size"+width+" "+height);
		CoordConvertor.setScreenSize(this.getWidth(),this.getHeight());
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		Log.e(TAG, "surfaceCreated");
		thread.setRunning(true);
		thread.start();
		Log.e(TAG, "size"+this.getWidth()+" "+this.getHeight());
		CoordConvertor.setScreenSize(this.getWidth(),this.getHeight());
	}

	@Override
	/*
	 * Callback invoked when the Surface has been destroyed and must no longer
	 * be touched. WARNING: after this method returns, the Surface/Canvas must
	 * never be touched again!
	 */
	public void surfaceDestroyed(SurfaceHolder holder) {
		// we have to tell thread to shut down & wait for it to finish, or else
		// it might touch the Surface after we return and explode
		boolean retry = true;
		thread.setRunning(false);
		while (retry) {
			try {
				thread.join();
				retry = false;
			} catch (InterruptedException e) {
			}
		}
	}

}
